<?php
/**
 * Class UserLogic
 * @package app\common\logic
 */

namespace app\common\logic;
use app\common\com\push\PushFactory;
use think\Log;

/**
 * 推送逻辑
 *
 * @package app\common\logic
 */
class Push extends Base
{

    /**
    * 对单个指定用户发起推送消息
    *
    * 注意：该方法不能放在事务当中!!!
    *
    * @author mayy
    * @date 2017-7-26
    * @param integer $user_id 用户id
    * @param string $user_type 用户类型 USER_
    * @param string $title 推送通知栏标题
    * @param string $content 推送通知栏内容
    * @param string $page 点击推送通知后要跳转的页面
    * @param array  $params 点击推送通知后跳转页面时要携带的参数
    * @return bool
    */
    public function sendPushToSingle($user_id, $user_type, $title, $content, $page = '', array $params = []) {
        if ($user_id <= 0 || empty($title) || empty($content)) {
            $this->errorInfo = '缺少必要的参数！';
            return false;
        }

        //0、参数处理
        if (!empty($params)) {
            $params = http_build_query($params);
        }

        //获取用户的client_id
        $client_id = $this->getUserClient($user_id, $user_type);
        if (empty($client_id)) {
            return false;
        }

        //2、发起推送
        $push = PushFactory::getPush(config('extra.push_config')['type']);
        $res = $push->sendToOne($client_id, $title, $content, $page, $params);

        //3、推送结果记录
        if ($res['result'] == 'ok') {
            //推送成功
            $not_must_data = [
                'page'      => $page,
                'params'    => $params,
            ];
            $this->recordPushLog($user_id, $user_type, 1, $title, $content, $not_must_data);
            return true;
        } else {
            //推送失败
            $this->errorInfo    = '推送失败！';
            $not_must_data      = [
                'fail_reason'   => $res['result'],
                'page'          => $page,
                'params'        => $params,
            ];
            $this->recordPushLog($user_id, $user_type, 0, $title, $content, $not_must_data);
            return false;
        }
    }

    /**
     * 获取用户的client_id
     *
     * @author mayy
     * @date 2017-9-27
     * @param $user_id
     * @param string $user_type 用户类型 admin:厂家用户 user：普通用户
     * @return bool | string
     */
    private function getUserClient($user_id, $user_type)
    {
        switch ($user_type) {
            case USER_TYPE_ADMIN_USER:
                $user_model = model('AdminUser');
                break;
            case USER_TYPE_NORMAL_USER:
                $user_model = model('User');
                break;
            default:
                $this->errorInfo = '用户类型参数错误！';
                Log::record('用户类型参数错误：' . $user_type);
                return false;
        }
        $user_info = $user_model->getInfo(['id' => $user_id], 'id, client_id,receive_push');
        unset($user_model);

        if (empty($user_info)) {
            $this->errorInfo = '用户信息不存在！';
            Log::record('用户('.$user_id.': '.$user_type.')不存在');
            return false;
        }

        if (empty($user_info['client_id'])) {
            $this->errorInfo = '用户client_id不存在，无法进行消息推送！';
            Log::record('用户('.$user_id.': '.$user_type.')client_id不存在');
            return false;
        }

        //不接收推送
        if ($user_info['receive_push'] == 0) {
            return false;
        }

        return $user_info['client_id'];
    }

    /**
     * 推送日志记录
     *
     * @author mayy
     * @date 2017-7-26
     * @param $user_id
     * @param string $user_type admin:厂家用户，normal：普通用户
     * @param $push_state
     * @param $title
     * @param $content
     * @param array $not_must_data
     * @return bool|int
     */
    private function recordPushLog($user_id, $user_type, $push_state, $title, $content, array $not_must_data = []){
        if ($user_id <= 0 || !in_array($push_state, [0,1]) || empty($title) || empty($content)) {
            $this->errorInfo = '推送日志记录缺少必要的参数！';
            return false;
        }

        $add_data = [
            'title'         => $title,
            'content'       => $content,
            'uid'           => $user_id,
            'user_type'     => $user_type,
            'push_state'    => $push_state,
        ];

        if (isset($not_must_data['client_id']) && !empty($not_must_data['client_id'])) {
            $add_data['client_id'] = $not_must_data['client_id'];
        }

        if (isset($not_must_data['page']) && !empty($not_must_data['page'])) {
            $add_data['page'] = $not_must_data['page'];
        }

        if (isset($not_must_data['params']) && !empty($not_must_data['params'])) {
            $add_data['params'] = $not_must_data['params'];
        }

        if (isset($not_must_data['fail_reason']) && !empty($not_must_data['fail_reason'])) {
            $add_data['fail_reason'] = $not_must_data['fail_reason'];
        }

        $push_log_model = model('PushLog');
        $res = $push_log_model->addData($add_data);
        if (!$res) {
            Log::write('推送日志记录失败！sql:' . $push_log_model->getLastSql());
        }
        unset($push_log_model);
        return $res;
    }
}